import { getLocalHistories } from '@/utils/storage'

// 初始数据
const initState = {
  // 搜索建议
  suggestion: [] as string[],
  // 历史记录
  histories: getLocalHistories(),
  results: [] as Article[],
}

export type Article = {
  title: string
  aut_id: number
  pubdate: string
  ch_id: number
  cover: {
    type: 0 | 1 | 3
    images: string[]
  }
  is_top: number
  art_id: string
  aut_name: string
  comm_count: number
  like_count: number
  collect_count: number
}

export type SearchAction =
  | { type: 'search/saveSuggestion'; payload: string[] }
  | { type: 'search/clearSuggestion' }
  | { type: 'search/saveHistory'; payload: string[] }
  | { type: 'search/clearHistory' }
  | { type: 'search/saveResult'; payload: Article[] }
  | { type: 'search/clearResult' }

// reducer 纯函数
export default function searchReducer(state = initState, action: SearchAction) {
  switch (action.type) {
    case 'search/saveSuggestion':
      return { ...state, suggestion: action.payload }
    case 'search/clearSuggestion':
      return { ...state, suggestion: [] }
    case 'search/saveHistory':
      return { ...state, histories: action.payload }
    case 'search/clearHistory':
      return { ...state, histories: [] }
    case 'search/saveResult':
      return { ...state, results: action.payload }
    case 'search/clearResult':
      return { ...state, results: [] }
    default:
      return state
  }
}
